import { defineStore } from 'pinia';
import { PermissionData, getCurrentUserInfo, queryPermission } from '@/api/userAndAuth';
import { store } from '../store';

interface PermissionStore {
  permissionList: PermissionData[];
  userInfo: Perm.UserInfo;
}

export const usePermissionStore = defineStore('permission', {
  state: (): PermissionStore => {
    return {
      permissionList: [],
      userInfo: {} as Perm.UserInfo,
    };
  },
  getters: {
    getPermissionList(): PermissionData[] {
      return this.permissionList;
    },
    getUserInfo(): Perm.UserInfo {
      return this.userInfo;
    },
  },
  actions: {
    setUserInfo(user: any) {
      this.userInfo = user;
    },
    async fetchPermissionList() {
      const data = await queryPermission({ targetUser: this.getUserInfo.userId });
      this.permissionList = data;
    },
    async fetchUserInfo() {
      const data = await getCurrentUserInfo();
      this.setUserInfo(data);
    },
  },
  persist: {
    enabled: true,
  },
});

// Need to be used outside the setup
export function usePermissionStoreWithOut() {
  return usePermissionStore(store);
}
